package pilgun.eshop.repository;

import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;

import pilgun.eshop.domain.User;

public class UserRepositoryTemplate implements UserRepository {
	
	private static final String INSERT_USER = "INSERT INTO Users (id, login, password, role) values (?, ?, ?, ?)";
	private static final String USER_SEL_QUERY = "SELECT id, login, password, role FROM Users";
	private static final String USER_SEL_QUERY_LOGIN = "SELECT id, login, password, role FROM Users WHERE login = ?";
    private static final String USER_SEL_QUERY_ID = "SELECT id, login, password, role FROM Users WHERE id = ?";
    
	private JdbcOperations template;
	
	@Autowired
	public UserRepositoryTemplate(JdbcOperations template) {
	this.template = template;
	}
	
	public void addToList(User user){
    	template.update(
    	        INSERT_USER,
    	        user.getId(), 
    	        user.getLogin(),
    	        user.getPassword(),
    	        user.getRole());
	}
	
	public User getUserByLogin(String login){
        return template.queryForObject(USER_SEL_QUERY_LOGIN, new RowMapper<User>(){
        	@Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User anUser = new User();
                anUser.setId(rs.getInt("id"));
                anUser.setLogin(rs.getString("login"));
                anUser.setPassword(rs.getString("password"));
                anUser.setRole(rs.getString("role"));
                return anUser;
            }
        }, 
        login);
    }
    
    public User getUserById(int id){
        return template.queryForObject(USER_SEL_QUERY_ID, new RowMapper<User>(){
        	@Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User anUser = new User();
                anUser.setId(rs.getInt("id"));
                anUser.setLogin(rs.getString("login"));
                anUser.setPassword(rs.getString("password"));
                anUser.setRole(rs.getString("role"));
                return anUser;
            }
        }, 
        id);
    }
    
    public List<User> getUserList(){
        return template.query(USER_SEL_QUERY,new RowMapper<User>(){
        	@Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            	User anUser = new User();
                anUser.setId(rs.getInt("id"));
                anUser.setLogin(rs.getString("login"));
                anUser.setPassword(rs.getString("password"));
                anUser.setRole(rs.getString("role"));
                return anUser;
            }
        });
        
    }
}
